import logging
from voice_assistant.commands.time_command import get_current_time
from voice_assistant.commands.weather_command import get_weather
from voice_assistant.commands.win_opt import execute_command
from voice_assistant.my_state import app_state  # 导入全局状态对象
from voice_assistant.ai.ollama_client import simple_generate
from voice_assistant.my_config import PROMPT_CMD, MODEL_NAME, MODEL_URL, PARAMS_PARSE

logger = logging.getLogger("VoiceAssistant")

def process_command(command_text):
    """处理识别到的指令"""
    logger.info(f"处理指令: {command_text}")
    # 非空判断
    if not command_text:
        return
    
    if "时间" in command_text:
        response = get_current_time()
    elif "天气" in command_text:
        response = get_weather()
    elif "打开下载" in command_text or "m3u8" in command_text:
        # 使用信号机制在主线程中启动 M3U8 下载工具
        from PyQt5.QtCore import QTimer
        from m3u8_pro.main import main as m3u8_main
        
        # 使用 QTimer.singleShot 在主事件循环中执行
        # 确保不会阻塞主线程或导致应用程序退出
        QTimer.singleShot(0, m3u8_main)
        response = "正在打开 M3U8 下载工具"
    elif "打开图片" in command_text or "图片下载" in command_text:
        # 使用image_pro模块替代旧的image模块
        from PyQt5.QtCore import QTimer
        from image_pro.main import main as image_pro_main
        
        # 使用QTimer.singleShot在主事件循环中执行，避免阻塞主线程
        QTimer.singleShot(0, image_pro_main)
        response = "正在打开图片下载工具Pro"
    else:
        # response = "未识别指令"
        response = ai_generate(command_text)
        logger.info(f"AI返回: {response}")
        if execute_command(response):
            response = "指令已执行"
        else:
            response = "指令不支持"
    app_state.active_commands.append(response)
       
def ai_generate(cont):
    try:
        prompt = PROMPT_CMD.format(cont=cont)
        response = simple_generate(prompt, model=MODEL_NAME, base_url=MODEL_URL, **PARAMS_PARSE)
    except Exception as e:
        response = f"发生错误: {str(e)}"
    finally:
        return response